/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { ArkFile, ts, AstTreeUtils } from "arkanalyzer";
import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger';
import { BaseChecker, BaseMetaData } from "../BaseChecker";
import { FileMatcher, MatcherCallback, MatcherTypes } from '../../Index';
import { Defects, IssueReport } from "../../model/Defects";
import { Rule } from "../../model/Rule";
import { RuleListUtil } from "../../utils/common/DefectsList";

const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'ExplicitModuleBoundaryTypesCheck');
const gMetaData: BaseMetaData = {
    severity: 1,
    ruleDocPath: "docs/explicit-module-boundary-types-check.md",
    description: "Require explicit return and argument types on exported functions' and classes' public class methods",
};
const defaultOptions: Options = {
    allowArgumentsExplicitlyTypedAsAny: false,
    allowDirectConstAssertionInArrowFunctions: true,
    allowedNames: [],
    allowHigherOrderFunctions: true,
    allowTypedFunctionExpressions: true,
}
interface Options {
    /** Whether to ignore arguments that are explicitly typed as `any`. */
    allowArgumentsExplicitlyTypedAsAny?: boolean;
    /**
     * Whether to ignore return type annotations on body-less arrow functions that return an `as const` type assertion.
     * You must still type the parameters of the function.
     */
    allowDirectConstAssertionInArrowFunctions?: boolean;
    /**
     * Whether to ignore return type annotations on functions immediately returning another function expression.
     * You must still type the parameters of the function.
     */
    allowHigherOrderFunctions?: boolean;
    /** Whether to ignore type annotations on the variable of a function expresion. */
    allowTypedFunctionExpressions?: boolean;
    /** An array of function/method names that will not have their arguments or return values checked. */
    allowedNames?: string[];
}

// 定义一个接口，用于存储函数或方法的行列信息
interface LocationInfo {
    fileName: string;
    line: number;
    character: number;
    description: string;
}

export class ExplicitModuleBoundaryTypesCheck implements BaseChecker {

    readonly metaData: BaseMetaData = gMetaData;
    public rule: Rule;
    public defects: Defects[] = [];
    public issues: IssueReport[] = [];

    private fileMatcher: FileMatcher = {
        matcherType: MatcherTypes.FILE,
    };

    public registerMatchers(): MatcherCallback[] {
        const fileMatcherCb: MatcherCallback = {
            matcher: this.fileMatcher,
            callback: this.check
        }
        return [fileMatcherCb];
    }

    public check = (target: ArkFile) => {
        const targetName = target.getName();
        if (targetName && this.getFileExtension(targetName) === ".ets") {
            return;
        }
        if (target instanceof ArkFile) {
            const code = target.getCode();
            if (!code) {
                return;
            }
            const filePath = target.getFilePath();
            const sourceFile = AstTreeUtils.getASTNode(target.getName(), code);
            const missingReturnTypes = this.checkExplicitBoundaryType(sourceFile);
            missingReturnTypes.forEach(info => {
                this.addIssueReportNode(info, filePath);
            });
        }
    }
    private getFileExtension(filePath: string): string {
        const lastDotIndex = filePath.lastIndexOf('.');
        if (lastDotIndex === -1) {
            return '';
        }
        return filePath.substring(lastDotIndex);
    }

    public checkExplicitBoundaryType(sourceFile: ts.SourceFile): LocationInfo[] {
        const result: LocationInfo[] = [];
        const Options: Options = this.rule && this.rule.option[0] ? this.rule.option[0] as Options : defaultOptions;

        function hasModifiers(node: ts.Node): node is ts.HasModifiers {
            return "modifiers" in node;
        }

        function isExported(node: ts.Node): boolean {
            if (hasModifiers(node)) {
                return !!ts.getModifiers(node)?.some(modifier => modifier.kind === ts.SyntaxKind.ExportKeyword);
            }
            return false;
        }

        function isParentExported(node: ts.Node): boolean {
            if (isExported(node)) return true;
            if (node.parent) return isParentExported(node.parent);
            return false;
        }

        function visit(node: ts.Node) {
            // 检查函数声明、方法声明、箭头函数等
            if (ts.isFunctionDeclaration(node)
                || ts.isArrowFunction(node)
                || ts.isFunctionExpression(node)
                || ts.isMethodSignature(node)
                || ts.isMethodDeclaration(node)) {

                // 特殊情况处理
                if (Options.allowDirectConstAssertionInArrowFunctions && ts.isArrowFunction(node) && ts.isDeleteExpression(node)) {
                    return;
                }
                if (Options.allowTypedFunctionExpressions && ts.isTypeOfExpression(node)) {
                    return;
                }
                if (Options.allowedNames && Options.allowedNames.length !== 0) {
                    let methodName: string | undefined;
                    methodName = node.name?.getText();
                    if (methodName && Options.allowedNames.includes(methodName)) {
                        return;
                    }
                }
                if (ts.isArrowFunction(node)) {
                    // 检查是否有返回类型注解
                    if (!node.type) {
                        const { line: arrowLine, character: arrowChar } = sourceFile.getLineAndCharacterOfPosition(node.equalsGreaterThanToken?.getStart() || node.getStart());
                        result.push({
                            fileName: sourceFile.fileName,
                            line: arrowLine + 1,
                            character: arrowChar + 1,
                            description: "Missing return type on function."
                        });
                    }

                    // 检查参数是否有类型注解
                    for (const param of node.parameters) {
                        if (!param.type) {
                            const { line: paramLine, character: paramChar } = sourceFile.getLineAndCharacterOfPosition(param.getStart());
                            result.push({
                                fileName: sourceFile.fileName,
                                line: paramLine + 1,
                                character: paramChar + 1,
                                description: `Argument '${param.name.getText()}' should be typed.`
                            });
                        } else if (param.type.kind === ts.SyntaxKind.AnyKeyword && !Options.allowArgumentsExplicitlyTypedAsAny) {
                            const { line: paramLine, character: paramChar } = sourceFile.getLineAndCharacterOfPosition(param.getStart());
                            result.push({
                                fileName: sourceFile.fileName,
                                line: paramLine + 1,
                                character: paramChar + 1,
                                description: `Argument '${param.name.getText()}' should be typed with a non-any type.`
                            });
                        }
                    }
                } else if (!node.type) {
                    const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
                    if (ts.getModifiers(node)?.some(modifier => modifier.kind === ts.SyntaxKind.ExportKeyword)) {
                        result.push({
                            fileName: sourceFile.fileName,
                            line: line + 1,
                            character: character + 8,
                            description: "Missing return type on function."
                        });
                    } else {
                        let current = node.parent;
                        let isExport = false;
                        const classDeclaration = current as ts.ClassDeclaration;
                        if (classDeclaration && ts.getModifiers(classDeclaration)?.some(modifier => modifier.kind === ts.SyntaxKind.ExportKeyword)) {
                            isExport = true;
                        }
                        if (isExport) {
                            result.push({
                                fileName: sourceFile.fileName,
                                line: line + 1,
                                character: character + 1,
                                description: "Missing return type on function."
                            });
                        }
                    }
                }
            }

            // 检查默认导出的函数或变量
            if (ts.isVariableStatement(node) || ts.isExportAssignment(node)) {
                let func: ts.FunctionLikeDeclaration | undefined;

                if (ts.isVariableStatement(node)) {
                    // 检查变量声明中的函数表达式
                    const declaration = node.declarationList.declarations[0];
                    if (declaration.initializer && ts.isFunctionExpression(declaration.initializer)) {
                        func = declaration.initializer;
                    }
                } else if (ts.isExportAssignment(node)) {
                    // 检查 export default 中的函数表达式
                    if (node.expression && ts.isFunctionExpression(node.expression)) {
                        func = node.expression;
                    } else if (node.expression && ts.isObjectLiteralExpression(node.expression)) {
                        // 检查 export default { foo } 或 { bar } 的情况
                        for (const prop of node.expression.properties) {
                            if (ts.isPropertyAssignment(prop) && prop.initializer && ts.isFunctionExpression(prop.initializer)) {
                                func = prop.initializer;
                            }
                        }
                    } else if (node.expression && ts.isArrayLiteralExpression(node.expression)) {
                        // 检查 export default [foo] 的情况
                        for (const element of node.expression.elements) {
                            if (ts.isFunctionExpression(element)) {
                                func = element;
                            }
                        }
                    }
                }

                if (func) {
                    // 检查返回类型注解
                    if (!func.type) {
                        const { line, character } = sourceFile.getLineAndCharacterOfPosition(func.getStart());
                        result.push({
                            fileName: sourceFile.fileName,
                            line: line + 1,
                            character: character + 1,
                            description: "Missing return type on function."
                        });
                    }

                    // 检查参数类型注解
                    for (const param of func.parameters) {
                        if (!param.type) {
                            const { line: paramLine, character: paramChar } = sourceFile.getLineAndCharacterOfPosition(param.getStart());
                            result.push({
                                fileName: sourceFile.fileName,
                                line: paramLine + 1,
                                character: paramChar + 1,
                                description: `Argument '${param.name.getText()}' should be typed.`
                            });
                        }
                    }
                }
            }

            // 检查类中的 getter、setter 和抽象方法
            if (ts.isClassDeclaration(node) && isParentExported(node)) {
                for (const member of node.members) {
                    if (ts.isGetAccessorDeclaration(member)) {
                        // Getter 方法应该有返回类型注解
                        if (!member.type) {
                            const { line, character } = sourceFile.getLineAndCharacterOfPosition(member.getStart());
                            result.push({
                                fileName: sourceFile.fileName,
                                line: line + 1,
                                character: character + 1,
                                description: `Getter '${member.name.getText()}' is missing a return type annotation.`
                            });
                        }
                    } else if (ts.isSetAccessorDeclaration(member)) {
                        // Setter 方法的参数应该有类型注解
                        const param = member.parameters[0];
                        if (!param.type) {
                            const { line, character } = sourceFile.getLineAndCharacterOfPosition(param.getStart());
                            result.push({
                                fileName: sourceFile.fileName,
                                line: line + 1,
                                character: character + 1,
                                description: `Setter parameter '${param.name.getText()}' should be typed.`
                            });
                        }
                    } else if (ts.isMethodDeclaration(member)) {
                        // 检查是否是抽象方法
                        const isAbstract = !!ts.getModifiers(member)?.some(modifier => modifier.kind === ts.SyntaxKind.AbstractKeyword);
                        if (isAbstract) {
                            // 抽象方法应该有返回类型注解和参数类型注解
                            if (!member.type) {
                                const { line, character } = sourceFile.getLineAndCharacterOfPosition(member.getStart());
                                result.push({
                                    fileName: sourceFile.fileName,
                                    line: line + 1,
                                    character: character + 1,
                                    description: `Abstract method '${member.name.getText()}' is missing a return type annotation.`
                                });
                            }
                            for (const param of member.parameters) {
                                if (!param.type) {
                                    const { line: paramLine, character: paramChar } = sourceFile.getLineAndCharacterOfPosition(param.getStart());
                                    result.push({
                                        fileName: sourceFile.fileName,
                                        line: paramLine + 1,
                                        character: paramChar + 1,
                                        description: `Argument '${param.name.getText()}' in abstract method should be typed.`
                                    });
                                }
                            }
                        }
                    }
                }
            }
            // 检查类的构造函数参数
            if (ts.isClassDeclaration(node) && isParentExported(node)) {
                for (const member of node.members) {
                    if (ts.isConstructorDeclaration(member)) {
                        // 检查构造函数的参数类型注解
                        for (const param of member.parameters) {
                            // 检查带有修饰符的参数（public、private、readonly）是否缺少类型注解
                            if (hasModifiers(param) && !param.type) {
                                const { line: paramLine, character: paramChar } = sourceFile.getLineAndCharacterOfPosition(param.getStart());
                                result.push({
                                    fileName: sourceFile.fileName,
                                    line: paramLine + 1,
                                    character: paramChar + 1,
                                    description: `Constructor parameter '${param.name.getText()}' should be typed.`
                                });
                            }
                        }
                    }
                }
            }

            ts.forEachChild(node, visit);
        }

        visit(sourceFile);
        return result;
    }

    private addIssueReportNode(loc: LocationInfo, filePath: string) {
        const severity = this.rule.alert ?? this.metaData.severity;
        if (loc.description) {
            this.metaData.description = loc.description;
        }
        let defect = new Defects(loc.line, loc.character, loc.character, this.metaData.description, severity,
            this.rule.ruleId, filePath, this.metaData.ruleDocPath, true, false, false);
        this.issues.push(new IssueReport(defect, undefined));
        RuleListUtil.push(defect);
    }
}
